package com.qf.job;

import com.qf.constant.CacheConstants;
import com.qf.constant.RabbitMQConstants;
import com.qf.feign.CacheFeign;
import com.qf.util.JavaMailUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.Set;
/*
    monitor监控mq的pre_send_sms_topic队列, 如果这个队列中的数据超过了N条,
     那么系统自动发送邮件给管理员邮箱, 说mq服务器要炸了, 赶快来修理. N可以在配置文件中设置.
    ,监听消息队列信息条数
 */
@Component
@Slf4j
public class MonitorQueueMessageJob implements SimpleJob {
    @Autowired
    private Channel channel;

    @Resource
    private CacheFeign cacheFeign;

    @Autowired
    private JavaMailUtil javaMailUtil;

    @Override
    public void execute(ShardingContext shardingContext) {
        /**
         * 监听MQ中的队列消息的数量
         * Producer - Connection - Channel(创建队列,创建交换机,发送消息)
         */

        //查询到现在所拥有的全部通道key信息.
        Set<String> keys = cacheFeign.keys(CacheConstants.CACHE_PREFIX_SMS_CHANNEL + "*");

        //遍历channelIds
        for (String key : keys){
            //从通道的key中获取通道id
            String channelId = key.substring(key.lastIndexOf(":") + 1);
            //声明队列名称
            String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + channelId;


            int messageCount = 0;
            try {
                //创建队列(如果队列存在,不用管)
                channel.queueDeclare(queueName,true,false,false,null);
                //获取队列中的消息数量
                messageCount = channel.queueDeclarePassive(queueName).getMessageCount();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //判断消息数量
            if(messageCount > 5){
                //给运维人员/开发人员发送邮件，通知消息堆积。。。。
                log.info("[监控模块] {}队列中的消息，出现了消息堆积，消息的数量为：{}",queueName,messageCount);
                //发送邮件
                try {
                    System.out.println("发送了邮件");
                    javaMailUtil.sendMailForQueue(queueName,messageCount);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }else {
                log.info("[监控模块] {}队列中的消息，没有出现堆积问题！",queueName);
            }
        }
    }

}
